package com.example.common.utils;

import com.example.entity.vo.UserVo;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.support.RequestContext;

public class CurrentUserUtil {

    public static HttpServletRequest getRequest() {
        RequestAttributes attributes = RequestContextHolder.currentRequestAttributes();
        if (attributes instanceof ServletRequestAttributes) {
            return ((ServletRequestAttributes) attributes).getRequest();
        }
        return null;
    }

    public static String getCurrentUsername() {
        HttpServletRequest request = getRequest();
        if (request == null) {
            throw new IllegalStateException("No request bound to current thread.");
        }

        String token = extractToken(request);
        if (token == null || !JwtUtils.validateToken(token)) {
            throw new IllegalStateException("Invalid or missing token.");
        }

        UserVo userVo = JwtUtils.getInfoFromToken(token);
        if (userVo == null) {
            throw new IllegalStateException("Invalid or missing user information.");
        }
        return userVo.getUsername();
    }


    public static UserVo getCurrentUser() {
        HttpServletRequest request = getRequest();
        if (request == null) {
            throw new IllegalStateException("No request bound to current thread.");
        }

        String token = extractToken(request);
        if (token == null || !JwtUtils.validateToken(token)) {
            throw new IllegalStateException("Invalid or missing token.");
        }
        return JwtUtils.getInfoFromToken(token);
    }

    private static String extractToken(HttpServletRequest request) {
        String header = request.getHeader("Authorization");
        if (header != null && header.startsWith("Bearer ")) {
            return header.substring(7);
        }
        return null;
    }
}
